package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"shop/models"
)

type ShopController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	price, _ := c.GetInt("price")
	wight, _ := c.GetInt("wight")
	num, _ := c.GetInt("num")
	newtime := c.GetString("newtime")
	var one = models.Shop1{
		Name:    name,
		Price:   price,
		Wight:   wight,
		Num:     num,
		Newtime: newtime,
	}
	err := models.DB.Create(&one).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
		}
		c.ServeJSON()
	}
}

type JsonPage struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Page    int         `json:"page"`
	Sumpage int         `json:"sumpage"`
	Size    int         `json:"size"`
	Count   int64       `json:"count"`
}

func (c *ShopController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Shop1{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size
	var all []models.Shop1
	name := c.GetString("name")
	where := map[string]string{}
	if name != "" {
		where["name"] = name
	}
	err := models.DB.Offset(offset).Where(where).Limit(size).Find(&all).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonPage{
			Code:    200,
			Msg:     "查询分页成功",
			Data:    all,
			Page:    page,
			Sumpage: sumpage,
			Size:    size,
			Count:   count,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Shop1{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "删除失败",
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Up() {
	name := c.GetString("name")
	price, _ := c.GetInt("price")
	wight, _ := c.GetInt("wight")
	num, _ := c.GetInt("num")
	newtime := c.GetString("newtime")
	id, _ := c.GetInt("id")
	var new1 = models.Shop1{
		Name:    name,
		Price:   price,
		Wight:   wight,
		Num:     num,
		Newtime: newtime,
	}
	err := models.DB.Where("id=?", id).Updates(&new1).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "修改失败",
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
		}
		c.ServeJSON()
	}
}
